// 用户数据服务类
import { UserModel, UserRole } from '../model/UserModel';
import { FileIOMock } from '../../mocks/fileioMock';

export class UserService {
  private static readonly FILE_PATH = 'users.json';
  
  /**
   * 获取所有用户
   * @returns 用户列表
   */
  public static async getAllUsers(): Promise<UserModel[]> {
    try {
      const users = await FileIOMock.readJSONFile(this.FILE_PATH);
      return users.map((item: any) => UserModel.fromJson(item));
    } catch (error) {
      console.error('Failed to get all users:', error);
      return [];
    }
  }
  
  /**
   * 根据ID获取用户
   * @param id 用户ID
   * @returns 用户对象，如果不存在返回null
   */
  public static async getUserById(id: string): Promise<UserModel | null> {
    try {
      const users = await this.getAllUsers();
      const user = users.find(item => item.getId() === id);
      return user || null;
    } catch (error) {
      console.error(`Failed to get user by id ${id}:`, error);
      return null;
    }
  }
  
  /**
   * 根据用户名获取用户
   * @param username 用户名
   * @returns 用户对象，如果不存在返回null
   */
  public static async getUserByUsername(username: string): Promise<UserModel | null> {
    try {
      const users = await this.getAllUsers();
      const user = users.find(item => item.getUsername() === username);
      return user || null;
    } catch (error) {
      console.error(`Failed to get user by username ${username}:`, error);
      return null;
    }
  }
  
  /**
   * 添加新用户
   * @param userModel 用户对象
   * @returns 是否添加成功
   */
  public static async addUser(userModel: UserModel): Promise<boolean> {
    try {
      // 设置唯一ID
      if (!userModel.getId()) {
        userModel.setId(UserModel.generateId());
      }
      
      // 检查用户名是否已存在
      const existingUser = await this.getUserByUsername(userModel.getUsername());
      if (existingUser) {
        console.error(`Username ${userModel.getUsername()} already exists`);
        return false;
      }
      
      const users = await this.getAllUsers();
      users.push(userModel);
      
      // 将所有用户对象转换为JSON并保存
      const usersJson = users.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, usersJson);
    } catch (error) {
      console.error('Failed to add user:', error);
      return false;
    }
  }
  
  /**
   * 更新用户
   * @param userModel 更新后的用户对象
   * @returns 是否更新成功
   */
  public static async updateUser(userModel: UserModel): Promise<boolean> {
    try {
      const users = await this.getAllUsers();
      const index = users.findIndex(item => item.getId() === userModel.getId());
      
      if (index === -1) {
        return false; // 用户不存在
      }
      
      // 检查用户名是否与其他用户重复
      const existingUser = await this.getUserByUsername(userModel.getUsername());
      if (existingUser && existingUser.getId() !== userModel.getId()) {
        console.error(`Username ${userModel.getUsername()} already exists`);
        return false;
      }
      
      // 更新用户
      users[index] = userModel;
      
      // 将所有用户对象转换为JSON并保存
      const usersJson = users.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, usersJson);
    } catch (error) {
      console.error(`Failed to update user ${userModel.getId()}:`, error);
      return false;
    }
  }
  
  /**
   * 删除用户
   * @param id 用户ID
   * @returns 是否删除成功
   */
  public static async deleteUser(id: string): Promise<boolean> {
    try {
      const users = await this.getAllUsers();
      const filteredUsers = users.filter(item => item.getId() !== id);
      
      if (filteredUsers.length === users.length) {
        return false; // 用户不存在
      }
      
      // 将过滤后的用户对象转换为JSON并保存
      const usersJson = filteredUsers.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, usersJson);
    } catch (error) {
      console.error(`Failed to delete user ${id}:`, error);
      return false;
    }
  }
  
  /**
   * 根据角色获取用户
   * @param role 用户角色
   * @returns 符合条件的用户列表
   */
  public static async getUsersByRole(role: UserRole): Promise<UserModel[]> {
    try {
      const users = await this.getAllUsers();
      return users.filter(item => item.getRole() === role);
    } catch (error) {
      console.error(`Failed to get users by role ${role}:`, error);
      return [];
    }
  }
  
  /**
   * 搜索用户
   * @param keyword 搜索关键词
   * @returns 符合条件的用户列表
   */
  public static async searchUsers(keyword: string): Promise<UserModel[]> {
    try {
      const users = await this.getAllUsers();
      const lowerKeyword = keyword.toLowerCase();
      
      return users.filter(item => 
        item.getUsername().toLowerCase().includes(lowerKeyword) ||
        item.getRealName().toLowerCase().includes(lowerKeyword) ||
        item.getEmail().toLowerCase().includes(lowerKeyword) ||
        item.getPhone().includes(keyword)
      );
    } catch (error) {
      console.error(`Failed to search users with keyword ${keyword}:`, error);
      return [];
    }
  }
}